from Products.validation.interfaces.IValidator import IValidator
from DateTime import DateTime

# The StartBeforeEnd class validates the date fields by checking that
# the end date comes after the start date.
class StartBeforeEnd:
    __implements__ = (IValidator,)

    def __init__(self, name):
        self.name = name

    def __call__(self, endDate, *args, **kwargs):
        instance = kwargs.get('instance', None)
        req = kwargs['REQUEST']
        startDate = DateTime(req.form.get('startdatetime', None))
        endDate = DateTime(endDate)
        if startDate > endDate:
            return """End date before start date."""
        return 1


# The overbooking class checks that the meeting room is free for the
# date range given if the meeting room is required.
class Overbooking:
    __implements__ = (IValidator,)

    def __init__(self, name):
        self.name = name

    def __call__(self, value, *args, **kwargs):
        # If value = 0 then this event does not require the meeting room.
        # Validation is unneccessary in this case.
        if value == 0:
            return 1
        instance = kwargs.get('instance', None)
        req = kwargs['REQUEST']
        startdate = DateTime(req.form.get('startdatetime', None))
        enddate = DateTime(req.form.get('enddatetime',  None))
        # Retrieves all events that overlap with booked meeting room times
        # ( THIS MAY INCLUDE ITSELF! ) 
        results = instance.portal_catalog.searchResults(
            meta_type = 'CalEvent',
            start={
                'query':(enddate),
                'range':'max',
            },
            end={
                'query':(startdate),
                'range':'min',
            },
            getResmeetingroom = 1,
        )
        # Creates a new list of overlapping events that does not include itself 
        overlaps = [ item for item in results if item['UID'] != instance.UID() ]
        # If no conflicts found, then valid
        if len(overlaps) == 0:
            return 1
        # If conflicts found, report to the user when the bookings have been made for
        # so they may correct it
        errorString = "Meeting room already booked during this time period by the following event(s): "
        for item in overlaps:
            errorString += item['Title'] + "; "
        return errorString
